package com.lujianfei.recyclerview.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

public class CustomRecyclerView extends RecyclerView {

    private OnItemLongClickListener onItemLongClickListener;

    private boolean disableMove;

    private GestureDetector mGestureDetector;
    private float lastX;
    private float lastY;

    public CustomRecyclerView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(@NonNull Context context) {
        mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                if (null != onItemLongClickListener) {
                    View childViewUnder = findChildViewUnder(lastX, lastY);
                    onItemLongClickListener.onItemLongClick(childViewUnder);
                }
            }
        });
    }

    public boolean isDisableMove() {
        return disableMove;
    }

    public void setDisableMove(boolean disableMove) {
        this.disableMove = disableMove;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (null != mGestureDetector) {
            mGestureDetector.onTouchEvent(event);
        }
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                lastX = event.getX();
                lastY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                return !disableMove && super.dispatchTouchEvent(event);
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    public interface OnItemLongClickListener {
        void onItemLongClick(View view);
    }
}
